import React, {Component} from 'react'
import Dimensions from 'react-dimensions'
import {fetchData} from '../../../components/AjaxConsumer'
import SelectUrl from '../../../components/SelectUrl'
import ListModelDetail from './SearchModel'
import moment from 'moment';
import styles from './index_ad.scss'
import {
    Form,
    Input,
    Tooltip,
    Icon,
    Row,
    Col,
    Select,
    Checkbox,
    Button,
    message,
    Modal,
    Radio,
    DatePicker
} from 'antd';
const RadioGroup = Radio.Group;
const FormItem = Form.Item;
const confirm = Modal.confirm;
// 主要表单组件
class SelfForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            url:this.props.url,
            getData: this.props.getData ? this.props.getData: {},
            contractUrl: '/base/data/contract/get',
            modelTypeUrl:'/base/dic/get/model_type_p',
            disabled:false,
            formData:{
                model:'',
                remark:'',
                type:'',
                outPlanTime:null,
            }
        };
        this.uuid = this.props.getData ? this.props.getData.data.length : 0;
        this.dbOutCode = this.props.dbOutCode
    }

    componentDidMount(){
        if(this.state.getData && this.state.getData != {}){
            console.log('-------componentDidMount----init----');
            let length = this.props.getData ? this.props.getData.data.length : 0;
            const data = this.state.getData.data;
            console.log(data)
            for(let i = 0; i < length; i++){
                if(i == 0){
                    // this.state.formData.model = data[0].model;
                }

                let model = 'names1_'+i;
                let productName = 'names0_'+i;
                let density = 'names2_'+i;
                let spec = 'names3_'+i;
                let requireAmount = 'names4_'+i;
                let grade = 'names6_'+i;
                let level = 'names7_'+i;
                this.props.form.setFieldsValue({[model]: data[i].model});
                this.props.form.setFieldsValue({[productName]: data[i].productName});
                this.props.form.setFieldsValue({[density]: data[i].density});
                this.props.form.setFieldsValue({[spec]: data[i].spec});
                this.props.form.setFieldsValue({[requireAmount]: data[i].requireAmount});
                this.props.form.setFieldsValue({[grade]: data[i].grade});
                this.props.form.setFieldsValue({[level]: data[i].level});
            }
        }
    }

    handleSubmit = (e) => {
        e.preventDefault();
        let dbOutCode = this.dbOutCode;
        this.props.form.validateFieldsAndScroll((err, fieldsValue) => {
            if (!err) {
                this.setState({loading: true});
                console.log('fieldsValue=== ', fieldsValue);
                ///alert(fieldsValue.datePicker);

                //发送ajax 控制请求数据规则，无值的设为空
                for (let item in fieldsValue) {
                    if (!fieldsValue[item]) {
                        fieldsValue[item] = ''
                    }
                }

                // 打印表单提交的值
                let arrfvList = new Array;

                let arrfvCommon = {
                    "type": fieldsValue.type,
                    "outPlanTime": fieldsValue.outPlanTime
                }

                let chk = 0;

                const { form } = this.props;

                const keys = form.getFieldValue('keys');
                keys.map((k, index) => {
                    if(fieldsValue[`names1_${k}`] != null && fieldsValue[`names1_${k}`] != ''){
                        let afv = {
                            "model": form.getFieldValue(`names1_${k}`),
                            "productName": form.getFieldValue(`names0_${k}`),
                            "density": form.getFieldValue(`names2_${k}`),
                            "spec": form.getFieldValue(`names3_${k}`),
                            "grade": form.getFieldValue(`names6_${k}`),
                            "level": form.getFieldValue(`names7_${k}`),
                            "unit": form.getFieldValue(`names5_${k}`),
                            "requireAmount": form.getFieldValue(`names4_${k}`)
                        }
                        let itemfv = Object.assign(afv,arrfvCommon);
                        arrfvList.push(itemfv);
                        chk = 1;
                    }
                });

                console.log('arrfvList=== ', arrfvList);

                if(chk == 0){
                    Modal.warning({
                    title: '提示',
                    content: '请添加成品型号和数量！',
                });
                    this.setState({loading: false});
                    return;
                }

                this.setState({loading: true});

                //在这里可以改造传给服务器的   values
                let url = '';
                url = this.state.url;
                console.log('this.state.url=== ', this.state.url);

                const options = {
                    //服务器的url
                    url: url,
                    type: 'post',
                    condition:  JSON.stringify(arrfvList),
                    contentType: 'application/json; charset=utf-8'
                };
                fetchData(this, options, (res) => {
                    //回调函数
                    if (res.code == 1) {
                        console.log("刷新List列表")
                        this.props.refreshHandle();
                        this.props.onCancel();
                        this.setState({
                            loading: false,
                            visible: false,
                            disabled:false
                        });
                        message.success('操作成功');                      
                        this.props.form.resetFields();
                        this.uuid=0
                        this.props.form.setFieldsValue(
                            {
                                keys:[]
                            }
                        );
                    }
                },(res) => {if (res.code != 1) { 
                        this.setState({loading: false})
                }})
            }
        });
    };

    onCancel= () => {
        this.props.form.resetFields(); 
       // console.log("'uid",this.uuid)
        this.uuid=0
        this.props.form.setFieldsValue(
            {
                keys:[]
            }
        );
        this.props.onCancel();
        this.setState({
            disabled:false,
        })
    };

    popClick= (value) => {
        const { form } = this.props;
        // const model = form.getFieldValue('model');
        // if(model == null){
            
        //     Modal.warning({
        //             title: '提示',
        //             content: '请选择型号！',
        //         });
        //     return;
        // }
        this.refs.listModelDetail.showModal(value);
        this.refs.listModelDetail.refreshHandle();
       // this.props.refreshHandle();
    };

    // 成品型号选择弹出模态框的统一回调函数
    getListModelDetailData = (resultData) =>{

        console.log("getListModelDetailData");
        let k = resultData.k;
        let model = `names1_${k}`;
        let unit = `names5_${k}`;
        let productName = `names0_${k}`;
        let density = `names2_${k}`;
        let spec = `names3_${k}`;
        let grade = `names6_${k}`;
        let level = `names7_${k}`;
        this.props.form.setFieldsValue(
            {
               [model]: resultData.model,
                [unit]: resultData.unit,
                [productName]: resultData.productName,
                [density]: resultData.density,
                [grade]: resultData.grade,
                [level]: resultData.level,
                [spec]: resultData.spec
            }
        );
    }

    //减少
    remove = (k) => {
        const { form } = this.props;
        // can use data-binding to get
        const keys = form.getFieldValue('keys');
        // We need at least one passenger
        if (keys.length === 1) {
            return;
        }

        // can use data-binding to set
        form.setFieldsValue({
            keys: keys.filter(key => key !== k),
        });
    };

    //增加
    add = () => {
        const model = this.props.form.getFieldValue('model');
        if(model ==''){
            Modal.warning({
                    title: '提示',
                    content: '请选择型号！',
                });
            return;
        }

        this.setState({
            disabled:true
        });
        this.uuid++;
        console.log("this.uuid" + this.uuid);
        const { form } = this.props;
        const keys = form.getFieldValue('keys');
        const nextKeys = keys.concat(this.uuid);
        form.setFieldsValue({
            keys: nextKeys,
        });
    };

    render() {
        const { getFieldDecorator, getFieldValue } = this.props.form;
        const data = this.state.getData.data;
        const colNumber = 12;//一行2个
        const itemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 10 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 14 },
            },
        };
        const formItemLayoutWithOutLabel = {
            wrapperCol: {
                xs: { span: 24, offset: 0 },
                sm: { span: 20, offset: 4 },
            },
        };
        let tempArr = [];
        for (let i = 0; i < this.uuid; i++){
            tempArr.push(i)
        }
        getFieldDecorator('keys', { initialValue: tempArr });
        const keys = getFieldValue('keys');
        let userDefined3value = getFieldValue("userDefined3")
        const formItems = keys.map((k, index) => {
            return (
                <div className={styles.formItemRow}>
                    <Row key={k}>
                        <Col span={6}>
                            <FormItem {...itemLayout} label='型号' >
                                {getFieldDecorator(`names1_${k}`, {
                                    initialValue:this.state.formData.model,
                                    rules: [{
                                        required: true,
                                        whitespace: true,
                                        message: "请填写",
                                    }],
                                })( <Input disabled id='names1_${k}'/>)}
                            </FormItem>
                        </Col>

                        <Col span={0}>
                            <FormItem {...itemLayout} label='单位' >
                                {getFieldDecorator(`names5_${k}`, {
                                    initialValue: this.state.formData.unit,
                                    rules: [{
                                    }],
                                })(<Input disabled id='names5_${k}' />)}
                            </FormItem>
                        </Col>
                         <Col span={1} >
                            <Icon
                                className="dynamic-delete-button"
                                type="search"
                                onClick={() => this.popClick(k)}
                            />
                        </Col>
                        <Col span={0}>
                            <FormItem {...itemLayout} label='品名' >
                                {getFieldDecorator(`names0_${k}`, {
                                    initialValue:this.state.formData.productName,
                                    rules: [{
                                    }],
                                })( <Input disabled id='names0_${k}' />)}
                            </FormItem>
                        </Col>
                        <Col span={0}>
                            <FormItem {...itemLayout} label='定量' >
                                {getFieldDecorator(`names2_${k}`, {
                                    initialValue:this.state.formData.density,
                                    rules: [{
                                    }],
                                })( <Input disabled id='names2_${k}' />)}
                            </FormItem>
                        </Col>
                        <Col span={0}>
                            <FormItem {...itemLayout} label='规格' >
                                {getFieldDecorator(`names3_${k}`, {
                                    initialValue:this.state.formData.spec,
                                    rules: [{
                                    }],
                                })( <Input disabled id='names3_${k}' />)}
                            </FormItem>
                        </Col>
                        <Col span={5}>
                            <FormItem {...itemLayout} label='等级' >
                                {getFieldDecorator(`names6_${k}`, {
                                    initialValue:this.state.formData.grade,
                                    rules: [{
                                        required: true,
                                        whitespace: true,
                                        message: "请填写",
                                    }],
                                })( 
                                // <Input placeholder="请填写" style={{ width: '70px' }} />
                                    <Select>
                                    <Option value="1">一等品</Option>
                                    <Option value="2">二等品</Option>
                                    <Option value="3">处理品</Option>
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={5}>
                            <FormItem {...itemLayout} label='级别' >
                                {getFieldDecorator(`names7_${k}`, {
                                    initialValue:this.state.formData.level,
                                    rules: [{
                                        required: true,
                                        whitespace: true,
                                        message: "请填写",
                                    }],
                                })( 
                                // <Input placeholder="请填写" style={{ width: '70px' }} />
                                    <Select>
                                    <Option value="A">A</Option>
                                    <Option value="B">B</Option>
                                    <Option value="C">C</Option>
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={5}>
                            <FormItem  {...itemLayout} label='数量'>
                                {getFieldDecorator(`names4_${k}`, {
                                    initialValue:'',// data.arr[index]?String(data.arr[index].names2):'',
                                   // validateTrigger: ['onChange', 'onBlur'],
                                    rules: [{
                                        required: true,
                                        whitespace: true,
                                        message: "请填写数量",
                                    }],
                                })(
                                    <Input placeholder="请填写" style={{ width:'70px', marginRight: 1 }} />
                                )}
                                {keys[keys.length-1]==k?(
                                <Icon
                                    className="dynamic-delete-button"
                                    type="minus-circle-o"
                                    disabled={keys.length === 1}
                                    onClick={() => this.remove(k)}
                                />):null}
                            </FormItem>
                        </Col>
                    </Row>
                </div>
            );
        });
        const formItemLayout = {
            labelCol: {
                xs: {span: 24},
                sm: {span: 6}
            },
            wrapperCol: {
                xs: {span: 24},
                sm: {span: 14}
            }
        };
        return (
            <Form
                //onSubmit={this.handleSubmit}
                style={{
                    backgroundColor: '#fff',
                    paddingTop: '20px',
                    paddingBottom: '20px'
                }}>
                <div style={{width:'96%',height:'auto',margin:'0 auto'}}>
                    {/* <Row>
                        <Col span={colNumber}>
                            <FormItem {...formItemLayout} label="型号">
                                {getFieldDecorator('model', {
                                    initialValue: this.state.formData.model?this.state.formData.model:'',
                                    rules: [
                                        {
                                            required: true,whitespace: true,message: '请输入型号'
                                        },{
                                            max:100,message: '输入内容应少于100个字符'
                                        }
                                    ]
                                })(
                            //       <SelectUrl url={this.state.contractUrl} type="get" dicCode="contractNo" dicName="contractNo"/>
                                    <Input type="textarea" rows={2} />
                                )}
                            </FormItem>
                        </Col>
                        <Col span={colNumber}>
                            <FormItem
                                {...formItemLayout}
                                label='备注'
                                hasFeedback>
                                {getFieldDecorator('remark', {
                                    initialValue: this.state.formData.remark?this.state.formData.remark:'',
                                    rules: [{
                                        required: false, message: '请输入!'
                                    }, {
                                        whitespace: true, message: '不能为空'
                                    }]
                                })(<Input type="textarea" rows={2} />)}
                            </FormItem>
                        </Col>
                    </Row> */}

                    <Row>
                        <Col span={colNumber}>
                            <FormItem {...formItemLayout} label="产品类型">
                                {getFieldDecorator('type', {
                                    initialValue: this.state.formData.type?this.state.formData.type:'',
                                    rules: [
                                        {
                                            required: true,whitespace: true,message: '请选择正品或样品'
                                        }
                                    ]
                                })(
                                    <Select>
                                        <option value="-1"></option>
                                        <option value="0">正品</option>
                                        <option value="1">样品</option>
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={colNumber}>
                            <FormItem {...formItemLayout} label='计划出库日期'>
                                {getFieldDecorator('outPlanTime', {
                                    initialValue: this.state.formData.outPlanTime?this.state.formData.outPlanTime:null,
                                    rules: []
                                })(
                                    <DatePicker showTime format="YYYY-MM-DD HH:mm:ss" />
                                )}
                            </FormItem>
                        </Col>
                    </Row>

                    <Row>
                        <Col span={10} style={{height:'33px'}}>
                            <div style={{fontSize:'14px',fontWeight:'bold'}}>
                                出库物料
                            </div>
                        </Col>
                        <Col span={2} style={{height:'33px', textAlign:"right", paddingRight:'30px'}}>
                            <FormItem className={styles.addFormItem} {...formItemLayoutWithOutLabel}>
                                <Button type="dashed" onClick={this.add} style={{ width: '120%' }}>
                                    <Icon type="plus" /> 增加物料
                                </Button>
                            </FormItem>
                        </Col>
                        {/* <hr/> */}
                    </Row>
                    <div className={styles.formBox}>
                        {formItems}
                    </div>
                    <div style={{width:'250px', height:'auto', clear:'both', padding:'20px 0', margin:'0px auto'}}>
                        <Button type="primary" onClick={this.handleSubmit}  size="large" loading={this.state.loading}>
                            {this.state.loading?'提交中...':'确定'}
                        </Button>
                        <Button
                            type="default"
                            style={{marginLeft: '50px'}}
                            size="large"
                            onClick={this.onCancel}
                        >
                            取消
                        </Button>

                        <ListModelDetail getTableData={this.getListModelDetailData} ref='listModelDetail' />
                    </div>
                </div>
            </Form>
        );
    }
}
let MyForm = Form.create()(SelfForm);


export default class EditPage extends Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            visible: false,
            url:'',
        };

    }
    handleOk = () => {
        // let result = this.state.resData;
        this.setState({
            visible: false,
        });
        this.refreshHandle();
    };

    handleCancel = () => {
        this.setState({
            visible: false,
            
        });
    };

    refreshHandle = () => {
        console.log("刷新List列表");
        this.props.refreshHandle();
    };

    // 成品手工出库任务新增(外部调用)
    addHandle  = () => {
        this.setState({
            visible: true,
            resData: '',
            url: '/product/hand/insertHand',
            formTitle: '成品手工出库任务新增'
        });
    };


    render() {
        return (
            <Modal
                style={{top: '20px'}}
                visible={this.state.visible}
                title={this.state.formTitle ? this.state.formTitle : '填写表单'}
                onOk={this.handleOk}
                onCancel={this.handleCancel}
                width={'900px'}
                footer=''
                maskClosable={false}
                closable={false}
            >
                <MyForm
                    ref='myForm'
                    dbOutCode = {this.state.dbOutCode}
                    url = {this.state.url}
                    getData={this.state.resData}
                    onCancel={this.handleCancel}
                    refreshHandle = {this.refreshHandle}
                />
            </Modal>
        );
    }
}
